<template>
  <div class="app-container">
    <!-- 策略开关 -->
    <el-form ref="statusForm" v-loading="statusLoading">
      <h2>{{strategyData.name}}</h2>
      <el-form-item>
        <!-- 关闭开关的渲染 -->
        <b v-if="showSwitch">
        <el-switch  v-model="strategyStatus" @change="updateStrategyStatus"></el-switch>
        </b><b v-else>
          <!-- 灰掉 -->
        <el-switch disabled  v-model="strategyStatus" @change="updateStrategyStatus"></el-switch>
        </b>
        <b v-if="strategyStatus" style="color:#03d203;margin-left:10px;">已开启</b><b v-else style="color:#f00;">已关闭</b>

        <!-- 重启开关的渲染 -->
        <el-button v-if="showRestart" size="small" type="text" @click="onRestartStrategy" :loading="restartStatus" style="margin-left:10px;">重启 </el-button>           
        
        <b v-if="UpdateJarStatus" style="color:#03d203;margin-left:10px;">
            <el-button size="small" type="text"   @click="onUpdateJar" >更新</el-button>
        </b>
        <b v-else style="color:#f00;margin-left:10px;">
          <el-button size="small" type="text"  disabled  >更新</el-button>
        </b>

        <!-- 显示策略基本信息 -->
        <span style="margin-left:10px;"> 入口类：{{strategyData.params}}</span>
        <span style="margin-left:10px;">Email: {{strategyData.email}}</span>

          <!-- 策略编辑按钮的渲染 -->
        <el-button v-if="showEditStrategy" size="small" type="text" style="margin-left:10px;" @click="handleEditStrategyBasic" >编辑</el-button>        
      </el-form-item>


      <el-form-item>
        <el-tag   v-for="item in exchangeData" class="exchange-tag">
          {{item.alias}}:
          <b v-if="showExchangeEdit">
            <span v-for="pair in item.pairs" style="cursor:pointer;" @click="handleEditExchange(item)" >{{ pair }}</span>
          </b><b v-else>
          <!-- 灰掉 -->
            <span v-for="pair in item.pairs" style="cursor:pointer;" >{{ pair }}</span>
          </b>
          
          <b v-if="showExchangeDelete" @click="handleDeleteExchange(item)" style="color:red;cursor:pointer;" >Ⅹ</b>
        </el-tag>
        <el-button v-if="showExchangeAdd" class="button-new-tag" size="small" @click="handleAddExchange">✚</el-button>
      </el-form-item>
    </el-form>

    <!-- 对应策略配置信息 -->
    <div class="cqt-box-item">
        <h3>策略参数配置<el-button type="text" v-if="strategyConfigShow" @click="strategyConfigShow = false">隐藏</el-button>
        <el-button type="text" v-else @click="strategyConfigShow = true">显示</el-button>
        <el-button v-if="showStrategyConfigAdd" type="primary" size="mini" @click="handleAddConfig()" >添加<i class="el-icon-upload el-icon--right"></i></el-button>
        </h3>
        <el-table
            :data="strategyConf"
            border
            stripe
            v-show="strategyConfigShow"
            style="width:100%">
            <el-table-column
                prop="name"
                label="配置名"
                align="center">
            </el-table-column>

            <el-table-column
                label="配置参数"
                align="center">
                <template slot-scope="scope">
                    {{ scope.row.type == 'json' ? JSON.stringify(scope.row.value) : scope.row.value }}
                </template>
            </el-table-column>

            <el-table-column
                prop="type"
                label="数据类型"
                align="center">
            </el-table-column>

            <el-table-column
                prop="describe"
                align="center"
                label="配置说明">
            </el-table-column>
            <el-table-column
                label="操作"
                align="center">
                <template slot-scope="scope">
                    <el-button
                        v-if="showStrategyConfigEdit"
                        size="mini"
                        @click="handleEditConfig(scope.$index, scope.row)">编辑</el-button>
                    <el-button
                         v-if="showStrategyConfigDelete"
                        size="mini"
                        type="danger"
                        @click="handleDeleteConfig(scope.$index, scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
    </div>

 <!-- 持久化信息 -->
     <div class="cqt-box-item">
        <h3>策略持久信息<el-button type="text" v-if="ormDataShow" @click="ormDataShow = false">隐藏</el-button>
            <el-button type="text" v-else @click="ormDataShow = true">显示</el-button>
        </h3>
        <div v-if="ormDataShow" id="orm-box">
          <pre>{{ ormData }}</pre>
        </div>
    </div>

   <!-- 收益曲线 -->
     <div class="cqt-box-item">
        <h3>策略收益曲线<el-button type="text" v-if="profitCurrentShow" @click="profitCurrentShow = false">隐藏</el-button>
            <el-button type="text" v-else @click="profitCurrentShow = true">显示</el-button>
        </h3>
        <div class="app-container">
          <div v-if="profitCurrentShow">
            <highcharts class="chart" :options="chartOptions" :updateArgs="updateArgs"></highcharts>
            <el-pagination
                background
                layout="prev, pager, next"
                @current-change="handleProfitCurrentChange"
                :page-size="pageRequest.pageSize"
                :current-page="pageRequest.currentPage"
                :total="total">
            </el-pagination>
          </div>
        </div>
    </div>


    <!-- 日志 -->
    <div class="cqt-box-item" id="log-box">
        <h3>策略日志信息
          <el-button type="primary" size="mini" @click="handleDowloadLog" >日志下载<i class="el-icon-upload el-icon--right"></i></el-button>
        </h3>
        
        <p class="cqt-caption"></p>
        <el-table
            :data="logData"
            style="width:100%;margin-bottom:-20px;">
            <el-table-column
                label="日期"
                width="220">
                <template slot-scope="scope">
                    <i class="el-icon-time"></i>
                    <span style="margin-left:10px">{{ scope.row.date }}</span>
                </template>
            </el-table-column>
            <el-table-column
                label="类型"
                align="center"
                width="120">
                <template slot-scope="scope">
                    <el-tag size="medium" type="success" v-if="scope.row.type == 'SELL'">{{ scope.row.type }}</el-tag>
                    <el-tag size="medium" v-else-if="scope.row.type == 'INFO'">{{ scope.row.type }}</el-tag>
                    <el-tag size="medium" type="warning" v-else-if="scope.row.type == 'WARN'">{{ scope.row.type }}</el-tag>
                    <el-tag size="medium" type="info" v-else-if="scope.row.type == 'BUY'">{{ scope.row.type }}</el-tag>
                    <el-tag size="medium" type="danger" v-else-if="scope.row.type == 'ERROR'">{{ scope.row.type }}</el-tag>
                    <el-tag size="medium" type="info" v-else>{{ scope.row.type }}</el-tag>
                </template>
            </el-table-column>
            <el-table-column
                prop="value"
                label="信息详情">
            </el-table-column>
        </el-table>
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[10, 20, 30, 40]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="logTotal">
        </el-pagination>
    </div>

    <!-- 交易所信息编辑 -->
    <el-dialog title="交易所资料编辑" :visible.sync="dialogExchangeFormVisible">
        <el-form :model="exchangeForm">
            <el-form-item label="交易所ID" label-width="120px">
                <el-input v-model="exchangeForm.id" auto-complete="off" disabled></el-input>
            </el-form-item>
            <el-form-item label="交易所名称" label-width="120px">
                <el-input v-model="exchangeForm.name" auto-complete="off" disabled></el-input>
            </el-form-item>
            <el-form-item label="交易对" label-width="120px">
                <el-select v-model="exchangeForm.symbol" multiple placeholder="请选择对应交易对" style="width:100%">
                    <el-option
                        v-for="item in exchangeForm.symbolList"
                        :key="item"
                        :label="item"
                        :value="item">
                    </el-option>
                </el-select>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="dialogExchangeFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="submitExchange">确 定</el-button>
        </div>
    </el-dialog>

      <!-- 交易信息的新增 -->
    <el-dialog title="交易新增" :visible.sync="dialogAddExchangeFromVisible">

        <el-form :model="nullObject">
              <el-form-item label="可选交易所" label-width="120px">
                    <el-select v-model="nullString" @change="changeExchange" placeholder="configForm.type">
                        <el-option
                            v-for="item in allExchanges"
                            :key="item.id"
                            :label="item.alias"
                            :value="item.id"
                            :disabled="item.disabled">
                        </el-option>
                    </el-select>
            </el-form-item> 
        </el-form>

        <el-form :model="nullObject">
             <el-form-item label="交易所ID" label-width="120px">
                <el-input v-model="AddExchangeForm.id" auto-complete="off" disabled></el-input>
            </el-form-item>
            <el-form-item label="交易所名称" label-width="120px">
                <el-input v-model="AddExchangeForm.name" auto-complete="off" disabled></el-input>
            </el-form-item>
            <el-form-item label="交易对" label-width="120px">
                <el-select v-model="AddExchangeForm.coinPairs" multiple placeholder="请选择对应交易对" style="width:100%">
                    <el-option
                        v-for="item in AddExchangeForm.coinPairs"
                        :key="item"
                        :label="item"
                        :value="item">
                    </el-option>
                </el-select>
            </el-form-item>



        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="dialogAddExchangeFromVisible = false">取 消</el-button>
            <el-button type="primary" @click="submitExchangeAdd">确 定</el-button>
        </div>
    </el-dialog>

<!-- 策略基本信息编辑 -->
    <el-dialog title="策略基本信息编辑" :visible.sync="dialogStrategyFormVisible">
        <el-form :model="strategyForm">
            <el-form-item label="策略ID" label-width="120px">
                <el-input v-model="strategyForm.id" auto-complete="off" disabled></el-input>
            </el-form-item>

            <el-form-item label="策略名称" label-width="120px">
                <el-input v-model="strategyForm.name" auto-complete="off" disabled ></el-input>
            </el-form-item>

            <el-form-item label="策略jar包名" label-width="120px">
                <el-input v-model="strategyForm.jarName" auto-complete="off"  disabled></el-input>
            </el-form-item>

             <el-form-item label="策略的入口类名" label-width="120px">
                <el-input v-model="strategyForm.params" auto-complete="off"  disabled></el-input>
            </el-form-item>

             <el-form-item label="策略管理者Email" label-width="120px">
                <el-input v-model="strategyForm.email" auto-complete="off" ></el-input>
            </el-form-item>

        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="dialogStrategyFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="submitStrategyBasic">确 定</el-button>
        </div>
    </el-dialog>


<!-- 策略配置信息编辑 -->
    <el-dialog title="策略配置信息编辑" :visible.sync="dialogConfigFormVisible">
        <el-form :model="configForm">
            <el-form-item label="配置名" label-width="120px">
                <el-input v-model="configForm.name" auto-complete="off" ></el-input>
            </el-form-item>

            <el-form-item label="配置参数" label-width="120px">
                <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4}" v-model="configForm.value" auto-complete="off" ></el-input>
            </el-form-item>

             <el-form-item label="数据类型" label-width="120px">
                <el-select v-model="configForm.type" placeholder="configForm.type">
                <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
                :disabled="item.disabled">
                </el-option>
                </el-select>
            </el-form-item> 

            
            <el-form-item label="配置说明" label-width="120px">
                <el-input v-model="configForm.describe" auto-complete="off" ></el-input>
            </el-form-item>

        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="dialogConfigFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="submitConfig">确 定</el-button>
        </div>
    </el-dialog>


<!-- 新增策略配置信息-->
    <el-dialog title="策略配置信息新增" :visible.sync="dialogConfigAddFormVisible">
        <el-form :model="AddconfigForm">
            <el-form-item label="配置名" label-width="120px">
                <el-input v-model="AddconfigForm.name" auto-complete="off" @change="checkConfigNameIsHave" ></el-input>
            </el-form-item>

            <el-form-item label="配置参数" label-width="120px">
                <el-input @change="checkConfigValueIsNull" type="textarea" :autosize="{ minRows: 3, maxRows: 20}" v-model="AddconfigForm.value" auto-complete="off" ></el-input>
            </el-form-item>

             <el-form-item label="数据类型" label-width="120px">
                <el-select @change="ChangeAddCSVConfig"  v-model="AddconfigForm.type" placeholder="请选择">
                  <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                  </el-option>
                </el-select>

               <el-button v-if="showCSVConfig" type="primary" size="mini" @click="handleAddCSVConfig()" >csv文件配置<i class="el-icon-upload el-icon--right"></i></el-button>
            </el-form-item> 

            <el-form-item label="配置说明" label-width="120px">
                <el-input v-model="AddconfigForm.describe" auto-complete="off" ></el-input>
            </el-form-item>

        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="dialogConfigAddFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="submitAddConfig">确 定</el-button>
        </div>
    </el-dialog>

      <!-- 策略配置信息支持CSV文件上传 -->
        <el-dialog title="策略配置信息编辑" :visible.sync="dialogConfigCSVVisible">
          <el-upload
            class="upload-demo"
            action="#"
            :auto-upload="false"
            :on-change="handleChange"
            :file-list="fileList3">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传CSV文件</div>
          </el-upload>

          <div slot="footer" class="dialog-footer">
              <el-button @click="dialogConfigCSVVisible = false">取 消</el-button>
              <el-button type="primary" @click="saveStrategyCSVConfig">确 定</el-button>
          </div>
        </el-dialog>
 


  </div>
</template>

<script>
import Vue from "vue";
import HighchartsVue from "highcharts-vue";
import Highcharts from "highcharts/highstock";
import { parseTime } from "../../utils/index.js";
import Papa from "papaparse";

Vue.use(HighchartsVue, { Highcharts });
import {
  getInfo,
  restartStrategy,
  updateStrategyStatus,
  getLog,
  getNewLogData,
  updateStrategyBasic,
  updateStrategyConfig,
  deleteStrategyConfig,
  addConfig,
  getNewProfitLog,
  getProfitLog,
  updateJarVersion,
  getOrmData,
  getUserStrategyLevel,
  downloadLogFile
} from "@/api/strategy";
import {
  updateExchange,
  deleteStrategyExchange,
  getAllExchanges,
  addExchange
} from "@/api/strategyExchange";

export default {
  data() {
    return {
      fileList3: [],
      dialogConfigCSVVisible: false,

      //csv文件支持的按钮显示
      showCSVConfig: false,

      //持久化信息
      ormDataShow: false,
      ormData: null,
      //jar包是否有更新
      UpdateJarStatus: false,

      updateArgs: [true, true, { duration: 1000 }],
      chartOptions: {
        chart: {
          type: "spline",
          zoomType: "x",
          panning: true,
          panKey: "shift"
        },
        xAxis: {
          type: "datetime",
          title: {
            text: "时间日期"
          },
          tickPixelInterval: 150,
          labels: {
            formatter: function() {
              return Highcharts.dateFormat("%m-%d %H:%M:%S", this.value);
            }
          }
        },
        yAxis: {
          title: {
            text: "收益金额"
          }
        },
        tooltip: {
          crosshairs: [true, true],
          xDateFormat: "%Y-%m-%d %H:%M:%S"
        },
        title: {
          text: "收益曲线"
        },
        subtitle: {
          text: null
        },
        credits: {
          enabled: false
        },
        plotOptions: {
          spline: {
            marker: {
              enabled: false
            }
          }
        },
        series: [
          {
            name: "收益",
            data: [],
            color: "#409EFF",
            showInLegend: false
          }
        ]
      },
      pageRequest: {
        pageSize: 60,
        currentPage: 1
      },
      total: 0,
      profitInterval: null,

      profitLogData: [],

      options: [
        {
          value: "json",
          label: "json",
          disabled: true
        },
        {
          value: "number",
          label: "number",
          disabled: true
        },
        {
          value: "string",
          label: "string",
          disabled: true
        },
        {
          value: "boolean",
          label: "boolean",
          disabled: true
        },
        {
          value: "csv",
          label: "csv",
          disabled: true
        }
      ],

      nullArray: [],
      nullObject: null,
      nullString: null,

      //策略ID
      strategyId: null,

      //策略初始化数据(项目更新后需要使用的)
      strategyData: {
        id: null,
        name: null,
        jarName: null,
        params: null,
        email: null
      },

      //策略的开启状态
      strategyStatus: false,

      //策略是否在重启状态中
      restartStatus: false,

      //策略状态更新是否在进行中
      statusLoading: false,

      //交易所是否显示
      exchangeShow: false,

      //策略对应的交易所信息
      exchangeData: [],

      //收益曲線是否显示
      profitCurrentShow: false,

      //策略信息是否显示
      strategyShow: false,

      //策略基本信息
      strategyInfo: [],

      //策略配置信息是否显示
      strategyConfigShow: false,

      //策略配置信息
      strategyConf: [],

      //策略日志信息
      logData: [],
      //最新日志数据
      NewLogData: [],
      //当前查询页面
      currentPage: 1,
      //页面条数
      pageSize: 20,
      //日志的总条数
      logTotal: 0,
      //最近一次查询的条数
      lastLineNumber: 0,

      //策略交易所编辑页面是否关闭
      dialogExchangeFormVisible: false,
      //策略基本信息编辑页面是否关闭
      dialogStrategyFormVisible: false,
      //策略基本信息编辑页面是否关闭
      dialogConfigFormVisible: false,

      //策略交易所信息编辑页面缓存数据
      exchangeForm: {
        id: null,
        name: null,
        symbol: null
      },
      //策略基本信息编辑页面缓存数据
      strategyForm: {
        id: null,
        name: null,
        jarName: null,
        params: null,
        email: null
      },
      //策略配置信息编辑页面缓存数据
      configForm: {
        name: null,
        value: null,
        type: null,
        describe: null
      },

      //新增内容配置

      // 策略新增交易所页面是否关闭
      dialogAddExchangeFromVisible: false,
      allExchanges: [],
      AddExchangeForm: {
        id: null,
        name: null,
        code: null,
        alias: null,
        publicKey: null,
        privateKey: null,
        disabled: null,
        coinPairs: []
      },

      dialogConfigAddFormVisible: false,
      //策略新增配置信息缓存
      AddconfigForm: {
        name: null,
        value: null,
        type: "string",
        describe: null
      },
      intervalid1: null,
      intervalid2: null,
      intervalid3: null,

      //当前用户操作该策略的权限级别
      level: null,

      //各个按钮的控件

      //关闭开关
      showSwitch: false,
      //重启开关
      showRestart: false,
      //策略基本信息编辑按钮
      showEditStrategy: false,
      //策略配置信息新增按钮
      showStrategyConfigAdd: false,
      //策略配置信息编辑按钮
      showStrategyConfigEdit: false,
      //策略配置信息删除按钮
      showStrategyConfigDelete: false,
      //策略配置的交易所信息的删除
      showExchangeDelete: false,
      //策略配置的交易所的编辑
      showExchangeEdit: false,
      //策略配置的交易所的新增
      showExchangeAdd: false
    };
  },

  created() {
    this.strategyId = this.$route.query.id;
    this.init();
    let i = document.createElement("input");
    i.setAttribute("type", "color");
  },

  // TODO 初始化收益曲线请求
  mounted() {
    this.initChart();
  },

  methods: {
    init() {
      // 初始化请求
      this.loadStrategyData();

      //初始化日志
      this.loadLogData();

      //更新日志
      this.getNewLogInfo();

      //获取持久化信息
      this.loadOrmLogData();
    },
    initChart() {
      //收益曲线的加载
      this.loadProfitLog();
      //收益曲线的定时
      this.getNewProfitLogInfo();

      //持久化信息定时
      this.getNewOrmLogInfo();

      //获取用户对应该策略的级别信息
      this.loadUserStrategyLevel();
    },

    //加载当前用户对应该策略的操作级别
    loadUserStrategyLevel() {
      var params = {
        strategyId: this.strategyId
      };

      getUserStrategyLevel(params).then(response => {
        this.level = response.data;

        //初始化按钮的渲染
        this.loadButtonByUserStrategyLevel();
      });
    },

    //通过用户对该策略的操作级别对页面进行渲染
    loadButtonByUserStrategyLevel() {
      //1.如果为高级管理员和创建者则表示全部开放
      //2.如果是可编辑者和仅可查看这则就根据等级进行渲染
      if (this.level == 2) {
        //3.可编辑者---------只需要开放参数配置信息的按钮权限
        this.showStrategyConfigAdd = true;
        this.showStrategyConfigEdit = true;
        this.showStrategyConfigDelete = true;
        this.showSwitch = true;
        this.showRestart = true;
      } else if (this.level == 3) {
        //4.仅可查看者-------默认全关
        return;
      } else {
        //5.管理员/创建者----全部打开
        this.buttonAllOpen();
      }
    },

    //按钮默认全开状态
    buttonAllOpen() {
      //关闭开关
      this.showSwitch = true;
      //重启开关
      this.showRestart = true;
      //策略基本信息编辑按钮
      this.showEditStrategy = true;
      //策略配置信息新增按钮
      this.showStrategyConfigAdd = true;
      //策略配置信息编辑按钮
      this.showStrategyConfigEdit = true;
      //策略配置信息删除按钮
      this.showStrategyConfigDelete = true;
      //策略配置的交易所信息的删除
      this.showExchangeDelete = true;
      //策略配置的交易所的编辑
      this.showExchangeEdit = true;
      //策略配置的交易所的新增
      this.showExchangeAdd = true;
    },

    loadProfitLog() {
      //调用后台获取收益曲线数据
      var params = {
        pageSize: this.pageRequest.pageSize,
        pageNumber: this.pageRequest.currentPage,
        strategyId: this.strategyId
      };

      getProfitLog(params).then(Response => {
        this.profitLogData = Response.data.data;
        //当收益曲线数据为空时隐藏起来
        if (this.profitLogData.length == 0) {
          this.profitCurrentShow = false;
          return;
        }

        this.total = Response.data.total;

        this.chartOptions.series[0].data = this.subStringProfitLogInfo(
          this.profitLogData
        );
        this.chartOptions.subtitle.text =
          "共" +
          this.total +
          "条，" +
          Math.ceil(this.total / this.pageRequest.pageSize) +
          "页";
      });
    },

    //定时刷新收益曲线---->一分钟刷新一次
    //定时刷新日志
    getNewProfitLogInfo() {
      this.intervalid2 = setInterval(() => {
        if (this.pageRequest.currentPage == 1) {
          this.loadNewProfitLog();
        }
      }, 1000 * 60);
    },

    loadNewProfitLog() {
      var params = {
        strategyId: this.strategyId,
        lastLineNumber: this.total
      };
      getNewProfitLog(params).then(Response => {
        var logData = Response.data.data;
        this.total = Response.data.total;
        for (let i = 0; i < logData.length; i++) {
          //曲线是顺序展示
          this.chartOptions.series[0].data.splice(
            this.chartOptions.series[0].data.length,
            0,
            logData[length - 1]
          );

          //删除曲线的首位
          this.chartOptions.series[0].data.splice(0, 1);
        }
      });
    },

    // 截取收益日志文件格式
    subStringProfitLogInfo(data) {
      var pointData = [];
      for (var i = 0; i < data.length; i++) {
        let logInfo = data[i].split(" "),
          timeStr = logInfo[0] + " " + logInfo[1],
          time = new Date(timeStr.replace(/-/g, "/")).getTime();
        pointData.push([time, parseFloat(logInfo[2])]);
      }

      // console.log("pointData:", pointData);
      return pointData;
    },
    handleProfitCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.pageRequest.currentPage = val;
      this.loadProfitLog();
    },

    //定时刷新日志
    getNewLogInfo() {
      this.intervalid1 = setInterval(() => {
        if (this.currentPage == 1) {
          this.loadNewLogData();
        }
      }, 5000);
    },

    //加载策略所有信息
    loadStrategyData() {
      getInfo(this.strategyId).then(response => {
        var data = response.data;

        //缓存策略整体信息
        this.strategyData = data;

        //策略基本信息
        this.strategyInfo = [data];

        //策略对应的交易所信息
        this.exchangeData = data.exchanges;

        //策略对应的配置参数信息
        this.strategyConf = data.config;

        //获取策略的当前状态
        this.strategyStatus = data.state ? true : false;

        //JAR包是否有更新的版本
        this.UpdateJarStatus = data.jarIsUpdate ? true : false;
      });
    },

    //加载日志信息
    loadLogData() {
      var data = {
        pageNumber: this.currentPage,
        pageSize: this.pageSize,
        strategyId: this.strategyId
      };

      getLog(data).then(response => {
        //因为后端封装了两层--所以先获取数据层
        var responseData = response.data;
        //给日志数据赋值
        this.logData = this.subStringLogInfo(responseData.data);
        //给日志总行数赋值
        this.logTotal = responseData.total;
      });
    },

    //定时获取最新的日志文件
    loadNewLogData() {
      this.loadLogData();
      // var data = {
      //   strategyId: this.strategyId,
      //   lastLineNumber: this.logTotal
      // };

      // getNewLogData(data).then(response => {
      //   //因为后端封装了两层--所以先获取数据层
      //   var responseData = response.data;
      //   if (responseData.data.length == 0) {
      //     return;
      //   }
      //   //给日志数据赋值
      //   this.NewLogData = this.subStringLogInfo(responseData.data);

      //   //给日志总行数赋值
      //   this.logTotal = responseData.total;

      //   for (let i = 0; i < this.NewLogData.length; i++) {
      //     //插入一条新数据
      //     this.logData.splice(0, 0, this.NewLogData[i]);
      //     //删除一条旧数据
      //     this.logData.pop();
      //   }
      // });
    },

    // 截取日志文件格式
    subStringLogInfo(data) {
      var logData = [];
      for (var i = 0; i < data.length; i++) {
        var item = data[i];
        let logInfo = /^(.*) \[(.*)\] (.*)$/.exec(item);

        let dateExec = logInfo[1].split(/\s+/);
        // console.log(dateExec)
        var date = dateExec[0] + " " + dateExec[1];
        var type = dateExec[2];

        let valueExec = /^(.*) (:) (.*)$/.exec(logInfo[3]);
        var value = valueExec[3];


        //判断是否有SELL、BUY关键字
        var sell=/^SELL\.*/
        var buy=/^BUY\.*/
        if(sell.test(value)){
          type='SELL'
        }if(buy.test(value)){
          type='BUY'
        }
        
        var log = {
          date: date,
          type: type,
          value: value
        };

        //往数组中存放
        logData.push(log);
      }

      console.debug(logData);
      return logData;
    },

    //设置策略的重启
    onRestartStrategy() {
      if (this.restartStatus) return;

      this.restartStatus = true;
      restartStrategy(this.strategyId).then(response => {
        this.$message("操作成功!");
        this.restartStatus = false;
        this.loadStrategyData();
      });
    },

    //更新策略当前状态
    updateStrategyStatus() {
      var state = 1;
      if (!this.strategyStatus) state = 0;

      //正处于状态修改中
      this.statusLoading = true;

      //准备更新状态的参数
      var params = { id: this.strategyId, state: state };

      updateStrategyStatus(params).then(response => {
        this.$message("操作成功!");
        //状态更新结束
        this.statusLoading = false;
        this.strategyStatus = state ? true : false;
      });
    },

    //交易所编辑页面（处理器）
    // handleEditExchange(index, row) {
    //   console.log(index, row);
    //   this.exchangeForm = {
    //     id: row.id,
    //     name: row.name,
    //     symbol: row.pairs,
    //     symbolList: row.totalPairs,
    //     index: index
    //   };
    //   this.dialogExchangeFormVisible = true;
    // },

    handleEditExchange(item) {
      this.exchangeForm = {
        id: item.id,
        name: item.name,
        symbol: item.pairs,
        symbolList: item.totalPairs
      };
      this.dialogExchangeFormVisible = true;
    },

    //策略基本信息编辑页面(处理器)
    handleEditStrategyBasic() {
      this.strategyForm = {
        id: this.strategyData.id,
        name: this.strategyData.name,
        jarName: this.strategyData.jarName,
        params: this.strategyData.params,
        email: this.strategyData.email
      };
      this.dialogStrategyFormVisible = true;
    },

    //策略配置信息编辑页面(处理器)
    handleEditConfig(index, row) {
      this.configForm = {
        name: row.name,
        value: row.type == "json" ? JSON.stringify(row.value) : row.value,
        type: row.type,
        describe: row.describe,
        index: index
      };
      this.dialogConfigFormVisible = true;
    },

    // 为策略新增交易所
    handleAddExchange() {
      var params = {
        strategyId: this.strategyId
      };

      getAllExchanges(params).then(response => {
        this.allExchanges = response.data;
        this.dialogAddExchangeFromVisible = true;
      });
    },

    //删除所选交易所
    handleDeleteExchange(item) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          //准备参数
          var params = {
            strategyId: this.strategyId,
            exchangeId: item.id
          };
          // TODO 发出删除请求
          deleteStrategyExchange(params).then(response => {
            for (let i = 0; i < this.exchangeData.length; i++) {
              if (item.id == this.exchangeData[i].id) {
                this.exchangeData.splice(i, 1);
              }
            }

            this.$message({
              type: "success",
              message: "删除成功!"
            });
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },

    //删除策略的某条配置信息
    handleDeleteConfig(index, row) {
      console.log(index, row);
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          //准备参数
          //先将该参数删除之后将所有配置信息重新提交
          this.strategyConf.splice(index, 1);
          var data = {
            strategyId: this.strategyId,
            config: JSON.stringify(this.strategyConf)
          };
          // TODO 发出删除请求
          deleteStrategyConfig(data).then(response => {
            this.$message({
              type: "success",
              message: "删除成功!"
            });
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },

    //日志文件的分页
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pageSize = val;
      this.currentPage = 1;
      this.loadLogData();
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.currentPage = val;
      this.loadLogData();
    },

    //更新策略对应的交易所信息
    submitExchange() {
      var data = {
        strategyId: this.strategyId,
        exchangeId: this.exchangeForm.id,
        pairs: this.exchangeForm.symbol.join(",")
      };

      // TODO 验证是否重复-->进行修改或者新增
      updateExchange(data)
        .then(response => {
          this.$message("操作成功!");
          this.dialogExchangeFormVisible = false;

          //重新加载一下
          this.loadStrategyData();
        })
        .catch(err => {
          console.log("请求错误", err);
        });
    },

    //更新策略的基本信息
    submitStrategyBasic() {
      var data = this.strategyForm;

      //TODO该方法可进行更新或者新增
      updateStrategyBasic(data)
        .then(response => {
          this.$message("操作成功");
          this.strategyData = this.strategyForm;
          this.dialogStrategyFormVisible = false;
        })
        .catch(err => {
          console.log("请求错误", err);
        });
    },

    //更新策略配置信息
    submitConfig() {
      (this.strategyConf[this.configForm.index].name = this.configForm.name),
        (this.strategyConf[this.configForm.index].type = this.configForm.type),
        (this.strategyConf[this.configForm.index].value =
          this.configForm.type == "json"
            ? JSON.parse(this.configForm.value)
            : this.configForm.type == "number"
              ? parseFloat(this.configForm.value)
              : this.configForm.value),
        (this.strategyConf[
          this.configForm.index
        ].describe = this.configForm.describe);
      var data = {
        strategyId: this.strategyId,
        config: JSON.stringify(this.strategyConf)
      };

      // TODO该方法进行策略配置的更新
      updateStrategyConfig(data)
        .then(response => {
          this.$message("操作成功!");

          this.dialogConfigFormVisible = false;
          //重新加载策略数据
          this.loadStrategyData();
        })
        .catch(err => {
          this.dialogConfigFormVisible = false;
        });
    },

    //当新增策略交易所时选择要增加的时交易所时触发
    changeExchange(val) {
      for (let i = 0; i < this.allExchanges.length; i++) {
        if (this.allExchanges[i].id == val) {
          this.AddExchangeForm = this.allExchanges[i];
          break;
        }
      }
    },

    //为策略新增一条交易所信息
    submitExchangeAdd() {
      var data = {
        strategyId: this.strategyId,
        exchangeId: this.AddExchangeForm.id,
        pairs: this.AddExchangeForm.coinPairs.join(",")
      };

      // TODO 验证是否重复-->进行修改或者新增
      addExchange(data)
        .then(response => {
          this.$message("操作成功!");
          this.dialogAddExchangeFromVisible = false;
          this.loadStrategyData();
          this.AddExchangeForm = {
            id: null,
            name: null,
            code: null,
            alias: null,
            publicKey: null,
            privateKey: null,
            disabled: null,
            coinPairs: []
          };
        })
        .catch(err => {
          this.dialogAddExchangeFromVisible = false;
          console.log("请求错误", err);
        });
    },

    //新增策略配置信息
    handleAddConfig() {
      this.dialogConfigAddFormVisible = true;
    },

    submitAddConfig() {
      //新增配置信息
      //校验是否为空
      //判断是否为空
      if (this.AddconfigForm.name == "" || this.AddconfigForm.name == null) {
        alert("该参数名称不能为空！");
        this.AddconfigForm.name = "";
        return;
      }

      for (let i = 0; i < this.strategyConf.length; i++) {
        if (this.AddconfigForm.name == this.strategyConf[i].name) {
          alert("该参数名称已被占用！请您重新命名！");
          this.AddconfigForm.name = "";
          return;
        }
      }

      if (this.AddconfigForm.value == "" || this.AddconfigForm.value == null) {
        alert("该参数名称不能为空！");
        this.AddconfigForm.value = "";
        return;
      }

      //校验数据类型
      if (this.AddconfigForm.type == "string") {
        if (!this.checkString(this.AddconfigForm.value)) {
          this.AddconfigForm.value = "";
          return;
        }
      } else if (this.AddconfigForm.type == "number") {
        if (!this.checkNumber(this.AddconfigForm.value)) {
          this.AddconfigForm.value = "";
          return;
        }
      } else if (this.AddconfigForm.type == "json") {
        if (!this.checkJsonString(this.AddconfigForm.value)) {
          this.AddconfigForm.value = "";
          return;
        }
      }

      //判断新增的配置是否为Json类型
      if (this.AddconfigForm.type == "json") {
        var temp = {};
        temp.value = JSON.parse(this.AddconfigForm.value);
        temp.name = this.AddconfigForm.name;
        temp.describe = this.AddconfigForm.describe;
        temp.type = this.AddconfigForm.type;

        this.strategyConf.splice(this.strategyConf.length + 1, 0, temp);
      } else if (this.AddconfigForm.type == "number") {
        var temp = {};
        temp.value = parseFloat(this.AddconfigForm.value);
        temp.name = this.AddconfigForm.name;
        temp.describe = this.AddconfigForm.describe;
        temp.type = this.AddconfigForm.type;

        this.strategyConf.splice(this.strategyConf.length + 1, 0, temp);
      } else {
        this.strategyConf.splice(
          this.strategyConf.length + 1,
          0,
          this.AddconfigForm
        );
      }

      var data = {
        strategyId: this.strategyId,
        config: JSON.stringify(this.strategyConf)
      };

      addConfig(data)
        .then(response => {
          this.$message = "新增成功";
          this.loadStrategyData();
          this.dialogConfigAddFormVisible = false;
          this.AddconfigForm = {
            name: null,
            value: null,
            type: null,
            describe: null
          };
        })
        .catch(err => {
          console.log(err);
        });
    },

    /**
     * 校验String类型数据
     */
    checkString(param) {
      if (!typeof param == "string") {
        alert("数据类型不符!请重新输入");
        param = "";
        return false;
      }

      return true;
    },

    /**
     * 校验number类型数据
     */
    checkNumber(param) {
      try {
        //判断是否为数字类型
        if (!isNaN(parseFloat(param))) {
          return true;
        }
      } catch (e) {}

      alert("数据类型不符!请重新输入");
      return false;
    },

    /**
     * 校验json类型数据
     */
    checkJsonString(str) {
      try {
        if (typeof JSON.parse(str) == "object") {
          return true;
        }
      } catch (e) {}
      alert("数据类型不符!请重新输入");
      return false;
    },

    /**
     * JAR包邮更新的时候触发更新jar包
     *
     */
    onUpdateJar() {
      var params = {
        strategyId: this.strategyId
      };

      updateJarVersion(params)
        .then(response => {
          this.$message("操作成功!");
          this.UpdateJarStatus = false;
          this.loadStrategyData();
        })
        .catch(err => {
          this.$message = err.msg;
        });
    },

    /**
     * 获取持久化信息数据
     */
    loadOrmLogData() {
      var params = {
        strategyId: this.strategyId
      };

      getOrmData(params).then(response => {
        this.ormData = response.data;
      });
    },

    //定时刷新持久化信息---->一分钟刷新一次
    //定时刷新日志
    getNewOrmLogInfo() {
      this.intervalid3 = setInterval(() => {
        this.loadOrmLogData();
      }, 1000 * 60);
    },

    /**
     *校验策略配置名是否已经存在
     */
    checkConfigNameIsHave(val) {
      for (let i = 0; i < this.strategyConf.length; i++) {
        if (val == this.strategyConf[i].name) {
          alert("该参数名称已被占用！请您重新命名！");
          this.AddconfigForm.name = "";
          return;
        }
      }
    },
    /**
     *校验策略配置名是否已经存在
     */
    checkConfigValueIsNull(val) {
      //判断是否为空
      if (val == "" || val == null) {
        alert("该参数值不能为空！");
        this.AddconfigForm.value = "";
        return;
      }
    },

    /**
     * 上传csv文件
     */
    handleChange(file, fileList) {
      this.fileList3 = fileList.slice(-1);
    },

    /**
     * 上传CSV文件
     */
    handleAddCSVConfig() {
      this.dialogConfigCSVVisible = true;
    },

    /**
     * 解析CSV文件内容
     */
    saveStrategyCSVConfig() {
      var Filename = this.fileList3[0].url,
        self = this;

      var value = Papa.parse(Filename, {
        download: true,
        encoding: "",
        skipEmptyLines: true,
        complete: function(results) {
          var data = results.data;
          var strList;
          for (let i = 0; i < data.length; i++) {
            var str;
            var strData = data[i];
            if (i == 0) {
              strList = strData + " \n ";
              continue;
            }

            strList += strData + " \n ";
          }
          value = strList.trim();

          //为配置参数的值赋值
          self.AddconfigForm.value = value;

          //退出文件上传页面
          self.dialogConfigCSVVisible = false;

          //改变参数类型为csv格式
          self.AddconfigForm.type = "csv";
        }
      });
    },

    /**
     * 当选择类型为CSV时按钮才显示
     */
    ChangeAddCSVConfig(val) {
      if (val == "csv") {
        this.showCSVConfig = true;
      } else {
        this.showCSVConfig = false;
      }
    },
    /**
     * 下载日志文件
     */
    handleDowloadLog() {
      window.open(process.env.BASE_API+"/strategy/download?strategyId=" + this.strategyId);

      // var params = {
      //   strategyId: this.strategyId
      // };
      // downloadLogFile(params).then(response =>{
      //   this.$message("操作成功!");
      // }).catch(err => {
      //     console.log("----",err)
      // });
    }


  },

  //切换页面时清除定时任务的请求
  beforeDestroy() {
    clearInterval(this.intervalid1);
    clearInterval(this.intervalid2);
    clearInterval(this.intervalid3);
  },
};
</script>
<style scoped>
.line {
  text-align: center;
}
.cqt-box-item h3 > button {
  margin-left: 20px;
}
.cell .el-tag {
  margin-left: 2px;
  margin-right: 2px;
}
.el-pagination {
  margin-top: 20px;
}
.el-table {
  margin-bottom: 10px;
}
.cqt-caption {
  font-size: 24px;
  color: #ccc;
  padding: 10px 20px;
  background-color: #f7f7f7;
  border-radius: 4px;
  margin: 0;
}
</style>
<style>
#log-box .el-table td {
  padding: 2px 0;
}

#exchangeAdd {
  float: right;
}

#orm-box {
  background-color: #ecf5ff;
  padding: 20px;
  border-radius: 4px;
  border: 1px solid #409eff;
  line-height: 23px;
  font-size: 14px;
  color: #606266;
}
pre {
  max-height: 240px;
  overflow-y: auto;
  white-space: pre-wrap; /* css3.0 */
  white-space: -moz-pre-wrap; /* Firefox */
  white-space: -pre-wrap; /* Opera 4-6 */
  white-space: -o-pre-wrap; /* Opera 7 */
  word-wrap: break-word; /* Internet Explorer 5.5+ */
}
.exchange-tag {
  margin-right: 8px;
}
.exchage-tag span {
}
.exchange-tag > span + span::before {
  content: "、";
}
h2 {
  color: #333;
  font-weight: inherit;
}
h2::before {
  content: "";
  border-left: 2px solid #333;
  padding-left: 14px;
}
</style>
